package com.xul.srb.oss.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.xul.srb.oss.service.FileService;
import com.xul.srb.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author xul
 * @create 2022-07-15 22:56
 */
@Service
public class FileServiceImpl implements FileService {

    /**
     * 文件上传
     *
     * @param inputStream
     * @param module
     * @param fileName
     * @return
     */
    @Override
    public String upLoad(InputStream inputStream, String module, String fileName) {


        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);

        // 判断服务器上的oos的bucket_name是否存在 不存在就创建bucket_name
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)) {
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            // 设置成公共读 文件
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        // 处理文件目录 avatar/2019/02/26/uuid + 文件后缀
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        // 构建日期
        String folder = new DateTime().toString("/yyyy/MM/dd/");
        String key = module + folder + fileName;
        // 将文件传送到阿里云
        ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);
        // 关闭ossClient
        ossClient.shutdown();
        // 返回文件的访问路径
        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + key;
    }

    /**
     * oss上文件的删除
     *
     * @param url
     */
    @Override
    public void removeByUrl(String url) {
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        //文件名（服务器上的文件路径）  https://srb-xul.oss-cn-shanghai.aliyuncs.com/2022/07/15/c8e47f3c-14cf-400d-b2b9-69469c4baf01.jpg
        String host = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/";
        String objectName = url.substring(host.length());
        // oss删除文件
        ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);
        ossClient.shutdown();
    }
}
